<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="类目名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入类目名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--      <el-form-item label="状态" prop="status">-->
      <!--        <el-select v-model="queryParams.status" placeholder="类目状态" clearable size="small">-->
      <!--          <el-option-->
      <!--            v-for="dict in dict.type.sys_normal_disable"-->
      <!--            :key="dict.value"-->
      <!--            :label="dict.label"-->
      <!--            :value="dict.value"-->
      <!--          />-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="primary"-->
      <!--          plain-->
      <!--          icon="el-icon-plus"-->
      <!--          size="mini"-->
      <!--          @click="handleAdd(1)"-->
      <!--          v-hasPermi="['base:category:add']"-->
      <!--        >新增-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠
        </el-button>
<!--        <el-button-->
<!--          type="info"-->
<!--          plain-->
<!--          icon="el-icon-upload2"-->
<!--          size="mini"-->
<!--          @click="handleImport"-->
<!--        >导入-->
<!--        </el-button>-->
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="categoryList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="name" label="类目名称"></el-table-column>
      <!--      <el-table-column prop="budgetUnit" label="工程预算单位">-->
      <!--        <template slot-scope="scope">-->
      <!--          <dict-tag :options="dict.type.unit_type" :value="scope.row.budgetUnit"/>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column prop="costUnit" label="成本预测单位">-->
      <!--        <template slot-scope="scope">-->
      <!--          <dict-tag :options="dict.type.unit_type" :value="scope.row.costUnit"/>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column prop="acwpUnit" label="实际费用单位">-->
      <!--        <template slot-scope="scope">-->
      <!--          <dict-tag :options="dict.type.unit_type" :value="scope.row.acwpUnit"/>-->
      <!--        </template>-->
      <!--      </el-table-column>-->

      <el-table-column prop="seq" label="排序" width="100"></el-table-column>

      <el-table-column label="创建时间" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['base:category:add']"
          >新增
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['base:category:edit']"
          >修改
          </el-button>
          <el-button
            v-if="scope.row.pid != 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['base:category:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px" label-position="left">
        <el-row>
          <el-col :span="24" v-if="form.pid !== 0">
            <el-form-item label="上级类目">
              <el-input v-model="form.pname" placeholder="请选择上级类目" clearable :disabled='true' :style="{width: '99%'}"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="类目名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入类目名称" clearable :style="{width: '97%'}"/>
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="form.pid != 0">
            <el-form-item label="显示排序" prop="seq">
              <el-input-number v-model="form.seq" :min="0" clearable :style="{width: '97%'}"/>
            </el-form-item>
          </el-col>
        </el-row>
        <div v-if="form.pid != 0">
          <h4 class="form-header">成本预测</h4>
          <el-row>
            <el-col :span="8">
              <el-form-item label="人工单位" prop="costUnit">
                <el-select v-model="form.costUnit" placeholder="请选择" clearable :style="{width: '97%'}">
                  <el-option
                    v-for="dict in dict.type.unit_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="材料单位" prop="clCostUnit">
                <el-select v-model="form.clCostUnit" placeholder="请选择" clearable :style="{width: '97%'}">
                  <el-option
                    v-for="dict in dict.type.unit_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="机械单位" prop="jxCostUnit">
                <el-select v-model="form.jxCostUnit" placeholder="请选择" clearable :style="{width: '97%'}">
                  <el-option
                    v-for="dict in dict.type.unit_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <h4 class="form-header">实际费用</h4>
          <el-row>
            <el-col :span="8">
              <el-form-item label="人工单位" prop="acwpUnit">
                <el-select v-model="form.acwpUnit" placeholder="请选择" clearable :style="{width: '97%'}">
                  <el-option
                    v-for="dict in dict.type.unit_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="材料单位" prop="clAcwpUnit">
                <el-select v-model="form.clAcwpUnit" placeholder="请选择" clearable :style="{width: '97%'}">
                  <el-option
                    v-for="dict in dict.type.unit_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="机械单位" prop="jxAcwpUnit">
                <el-select v-model="form.jxAcwpUnit" placeholder="请选择" clearable :style="{width: '97%'}">
                  <el-option
                    v-for="dict in dict.type.unit_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <el-col>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
          </el-form-item>
        </el-col>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">

          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getSeqByPid,
  listCategory,
  getCategory,
  delCategory,
  addCategory,
  updateCategory
} from "@/api/base/category";
import {getToken} from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Category",
  dicts: ['unit_type', "sys_normal_disable"],
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      categoryList: [],
      // 部门树选项
      cateGoryOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 是否展开
      expand: false,
      // 查询参数
      queryParams: {
        name: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        pid: [
          {required: true, message: "上级类目不能为空", trigger: "blur"}
        ],
        name: [
          {required: true, message: "类目名称不能为空", trigger: "blur"}
        ],
        seq: [
          {required: true, message: "显示排序不能为空", trigger: "blur"}
        ],
        costUnit: [
          {required: true, message: "人工单位", trigger: 'change'}
        ],
        clCostUnit: [
          {required: true, message: "材料单位", trigger: 'change'}
        ],
        jxCostUnit: [
          {required: true, message: "机械单位", trigger: 'change'}
        ],
        acwpUnit: [
          {required: true, message: "人工单位", trigger: 'change'}
        ],
        clAcwpUnit: [
          {required: true, message: "材料单位", trigger: 'change'}
        ],
        jxAcwpUnit: [
          {required: true, message: "机械单位", trigger: 'change'}
        ],
        budgetUnit: [
          {required: true, message: "人工单位", trigger: 'change'}
        ],
        clBudgetUnit: [
          {required: true, message: "材料单位", trigger: 'change'}
        ],
        jxBudgetUnit: [
          {required: true, message: "机械单位", trigger: 'change'}
        ]

      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（工人导入）
        open: false,
        // 弹出层标题（工人导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/product/importData"
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询部门列表 */
    getList() {
      this.loading = true;
      listCategory(this.queryParams).then(response => {
        console.log(response);
        this.categoryList = this.handleTree(response.data, "id", "pid");
        console.log(this.categoryList)
        this.loading = false;
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        pid: undefined,
        name: undefined,
        seq: undefined,
        status: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      console.log(row)
      this.reset();
      if (0 == row) {
        this.form.pid = 0
      } else {
        this.form.pid = row.id;
        this.form.pname = row.name
      }
      getSeqByPid(this.form.pid).then(Response => {
        this.form.seq = Response.data.seq
      });
      this.open = true;
      this.title = "添加类目";

    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getCategory(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改类目";
      });

    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateCategory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCategory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除名称为"' + row.name + '"的数据项？').then(function () {
        return delCategory(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导入按钮操作 */
    handleImport() {

      this.upload.title = "产品导入";
      this.upload.open = true;
      console.log(this.upload)
    }
    ,
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/category/export', {
        ...this.queryParams
      }, `product_${new Date().getTime()}.xlsx`)
    }
    ,
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/category/importTemplate', {
        ...this.queryParams
      }, `product_${new Date().getTime()}.xlsx`)
    }
    ,
// 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
// 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", {dangerouslyUseHTMLString: true});
      this.queryParams.pageNum = 1
      this.getList();
    }
    ,
// 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
